package cn.springcloud.fix.user.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

@Slf4j
@Service
public class OrderService {

    private ApplicationEventPublisher applicationEventPublisher;

    @Transactional
    public void finishOrder(Object order) {
        // 修改订单成功
        updateOrderSuccess(order);
        // 发布 Spring Event 事件，发送消息时间过长时会占用数据库连接，所以就要把数据库操作与发送消息到 MQ 解耦开来
        applicationEventPublisher.publishEvent(new MyAfterTransactionEvent(null, order));
    }

    @Slf4j
    @Component
    private static class MyTransactionListener {

        //@Autowired
        //private MqService mqService;

        @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
        private void onHelloEvent(MyAfterTransactionEvent event) {
            Object order = event.getOrder();
            //mqService.send(order);
        }
    }

    // 定一个事件，继承自ApplicationEvent
    private static class MyAfterTransactionEvent extends ApplicationEvent {

        private Object order;

        public MyAfterTransactionEvent(Object source, Object order) {
            super(source);
            this.order = order;
        }

        public Object getOrder() {
            return order;
        }
    }

    private void updateOrderSuccess(Object order) {

    }
}
